﻿using AspNetDemo.Models;
using AspNetDemo.Services;
using NHibernate.Linq;
using System.Linq;
using System.Web.Http;

namespace AspNetDemo.Controllers
{
    [RoutePrefix("api/stus")]
    public class DefaultApiController : ApiController
    {
        private readonly SessionHelper _sessionHelper;

        public DefaultApiController(SessionHelper sessionHelper)
        {
            _sessionHelper = sessionHelper;
        }

        [Route("")]
        [ArgumentExceptionHandler]
        public IHttpActionResult GetStudents()
        {
            using (var session = _sessionHelper.GetSession())
            {
                return Ok(session.Query<Student>().SetOptions(x => x.SetCacheable(true)).Where(x=>true).ToList());
            }
        }

        [Route("{id:int}")]
        public IHttpActionResult GetStudent(int id)
        {
            using (var session = _sessionHelper.GetSession())
            {
                return Ok(session.Get<Student>(id));
            }
        }

        [Route("{id:int}")]
        public IHttpActionResult DeleteStudent(int id)
        {
            using (var session = _sessionHelper.GetSession())
            {
                session.Delete(session.Get<Student>(id));
            }

            return Ok();
        }

        [Route("")]
        [HttpPost]
        public IHttpActionResult CreateStudent(Student stu)
        {
            using (var session = _sessionHelper.GetSession())
            {
                session.Save(stu);
            }

            return Ok();
        }
    }
}
